<template>
  <div class="menu-container">
    <a-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <a-form
          :model="searchForm"
          layout="inline"
          @submit="handleSearch"
        >
          <a-form-item label="菜单名称">
            <a-input
              v-model="searchForm.menuName"
              placeholder="请输入菜单名称"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              allow-clear
            >
              <a-option :value="1">启用</a-option>
              <a-option :value="0">禁用</a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮 -->
      <div class="table-actions">
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-plus />
          </template>
          新增菜单
        </a-button>
        <a-button
          type="outline"
          @click="toggleExpand"
        >
          <template #icon>
            <icon-menu-unfold v-if="!expandAll" />
            <icon-menu-fold v-else />
          </template>
          {{ expandAll ? '折叠' : '展开' }}全部
        </a-button>
      </div>

      <!-- 菜单表格 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="false"
        :expand-all-rows="expandAll"
        row-key="id"
      >
        <template #menuType="{ record }">
          <a-tag :color="getMenuTypeColor(record.menuType)">
            {{ getMenuTypeText(record.menuType) }}
          </a-tag>
        </template>

        <template #icon="{ record }">
          <component :is="record.icon" v-if="record.icon" />
          <span v-else>-</span>
        </template>

        <template #visible="{ record }">
          <a-tag :color="record.visible === 1 ? 'green' : 'red'">
            {{ record.visible === 1 ? '显示' : '隐藏' }}
          </a-tag>
        </template>

        <template #status="{ record }">
          <a-switch
            v-model="record.status"
            :checked-value="1"
            :unchecked-value="0"
            @change="handleStatusChange(record)"
          />
        </template>

        <template #actions="{ record }">
          <a-button size="small" @click="handleEdit(record)">编辑</a-button>
          <a-button size="small" @click="handleAddChild(record)">新增</a-button>
          <a-popconfirm
            content="确定要删除这个菜单吗？"
            @ok="handleDelete(record)"
          >
            <a-button size="small" status="danger">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>

    <!-- 菜单表单弹窗 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      width="800px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="上级菜单" field="parentId">
              <a-tree-select
                v-model="formData.parentId"
                :data="menuTreeData"
                :field-names="{ key: 'id', title: 'menuName', children: 'children' }"
                placeholder="选择上级菜单"
                allow-clear
                allow-search
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="菜单类型" field="menuType">
              <a-radio-group v-model="formData.menuType">
                <a-radio :value="1">目录</a-radio>
                <a-radio :value="2">菜单</a-radio>
                <a-radio :value="3">按钮</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="菜单名称" field="menuName">
              <a-input v-model="formData.menuName" placeholder="请输入菜单名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="显示排序" field="sort">
              <a-input-number v-model="formData.sort" placeholder="请输入排序" :min="0" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16" v-if="formData.menuType !== 3">
          <a-col :span="12">
            <a-form-item label="菜单图标" field="icon">
              <a-input v-model="formData.icon" placeholder="请输入图标名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="路由地址" field="path">
              <a-input v-model="formData.path" placeholder="请输入路由地址" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16" v-if="formData.menuType === 2">
          <a-col :span="12">
            <a-form-item label="组件路径" field="component">
              <a-input v-model="formData.component" placeholder="请输入组件路径" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="权限标识" field="permission">
              <a-input v-model="formData.permission" placeholder="请输入权限标识" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16" v-if="formData.menuType === 3">
          <a-col :span="12">
            <a-form-item label="权限标识" field="permission">
              <a-input v-model="formData.permission" placeholder="请输入权限标识" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="显示状态" field="visible">
              <a-radio-group v-model="formData.visible">
                <a-radio :value="1">显示</a-radio>
                <a-radio :value="0">隐藏</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="菜单状态" field="status">
              <a-radio-group v-model="formData.status">
                <a-radio :value="1">正常</a-radio>
                <a-radio :value="0">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="formData.menuType !== 3">
            <a-form-item label="是否缓存" field="isCache">
              <a-radio-group v-model="formData.isCache">
                <a-radio :value="1">缓存</a-radio>
                <a-radio :value="0">不缓存</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formData.remark"
            placeholder="请输入备注"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'

// 搜索表单
const searchForm = reactive({
  menuName: '',
  status: undefined
})

// 表格数据
const tableData = ref([])
const menuTreeData = ref([])
const loading = ref(false)
const expandAll = ref(false)

// 表格配置
const columns: TableColumnData[] = [
  { title: '菜单名称', dataIndex: 'menuName', width: 200 },
  { title: '图标', slotName: 'icon', width: 80 },
  { title: '排序', dataIndex: 'sort', width: 80 },
  { title: '权限标识', dataIndex: 'permission', width: 200 },
  { title: '组件路径', dataIndex: 'component', width: 200 },
  { title: '菜单类型', slotName: 'menuType', width: 100 },
  { title: '显示状态', slotName: 'visible', width: 100 },
  { title: '状态', slotName: 'status', width: 80 },
  { title: '创建时间', dataIndex: 'createTime', width: 160 },
  { title: '操作', slotName: 'actions', width: 200, fixed: 'right' }
]

// 表单相关
const formVisible = ref(false)
const formTitle = ref('')
const formRef = ref()
const formData = reactive({
  id: undefined,
  parentId: 0,
  menuName: '',
  menuType: 1,
  path: '',
  component: '',
  permission: '',
  icon: '',
  sort: 0,
  visible: 1,
  status: 1,
  isCache: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  menuName: [
    { required: true, message: '请输入菜单名称' },
    { minLength: 2, message: '菜单名称至少2个字符' }
  ],
  menuType: [
    { required: true, message: '请选择菜单类型' }
  ],
  path: [
    { required: true, message: '请输入路由地址' }
  ],
  component: [
    { required: true, message: '请输入组件路径' }
  ]
}

// 工具方法
const getMenuTypeColor = (menuType: number) => {
  const colors = { 1: 'blue', 2: 'green', 3: 'orange' }
  return colors[menuType] || 'gray'
}

const getMenuTypeText = (menuType: number) => {
  const texts = { 1: '目录', 2: '菜单', 3: '按钮' }
  return texts[menuType] || '未知'
}

// 搜索
const handleSearch = () => {
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    menuName: '',
    status: undefined
  })
  handleSearch()
}

// 切换展开
const toggleExpand = () => {
  expandAll.value = !expandAll.value
}

// 新增
const handleAdd = () => {
  formTitle.value = '新增菜单'
  resetForm()
  formVisible.value = true
  fetchMenuTree()
}

// 新增子菜单
const handleAddChild = (record: any) => {
  formTitle.value = '新增子菜单'
  resetForm()
  formData.parentId = record.id
  formVisible.value = true
  fetchMenuTree()
}

// 编辑
const handleEdit = (record: any) => {
  formTitle.value = '编辑菜单'
  Object.assign(formData, record)
  formVisible.value = true
  fetchMenuTree()
}

// 删除
const handleDelete = async (record: any) => {
  try {
    // 调用删除API
    Message.success('删除成功')
    fetchData()
  } catch (error) {
    Message.error('删除失败')
  }
}

// 状态切换
const handleStatusChange = async (record: any) => {
  try {
    // 调用状态切换API
    Message.success(`${record.status ? '启用' : '禁用'}成功`)
  } catch (error) {
    // 恢复原状态
    record.status = record.status ? 0 : 1
    Message.error('操作失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  const errors = await formRef.value?.validate()
  if (errors) return

  try {
    if (formData.id) {
      // 更新菜单
      Message.success('更新成功')
    } else {
      // 新增菜单
      Message.success('新增成功')
    }
    formVisible.value = false
    fetchData()
  } catch (error) {
    Message.error('操作失败')
  }
}

// 取消表单
const handleCancel = () => {
  formVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    parentId: 0,
    menuName: '',
    menuType: 1,
    path: '',
    component: '',
    permission: '',
    icon: '',
    sort: 0,
    visible: 1,
    status: 1,
    isCache: 0,
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 获取菜单树数据
const fetchMenuTree = async () => {
  try {
    // 模拟菜单树数据
    const mockMenuTree = [
      {
        id: 0,
        menuName: '主类目',
        children: [
          {
            id: 1,
            menuName: '系统管理',
            children: [
              { id: 11, menuName: '用户管理' },
              { id: 12, menuName: '角色管理' },
              { id: 13, menuName: '菜单管理' }
            ]
          },
          {
            id: 2,
            menuName: '系统监控',
            children: [
              { id: 21, menuName: '在线用户' },
              { id: 22, menuName: '操作日志' }
            ]
          }
        ]
      }
    ]
    menuTreeData.value = mockMenuTree
  } catch (error) {
    Message.error('获取菜单树失败')
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟菜单数据
    const mockData = [
      {
        id: 1,
        parentId: 0,
        menuName: '系统管理',
        menuType: 1,
        path: '/system',
        component: null,
        permission: null,
        icon: 'icon-settings',
        sort: 1,
        visible: 1,
        status: 1,
        isCache: 0,
        createTime: '2024-01-01 00:00:00',
        children: [
          {
            id: 11,
            parentId: 1,
            menuName: '用户管理',
            menuType: 2,
            path: '/system/user',
            component: 'system/user/index',
            permission: 'system:user:list',
            icon: 'icon-user',
            sort: 1,
            visible: 1,
            status: 1,
            isCache: 1,
            createTime: '2024-01-01 00:00:00'
          },
          {
            id: 12,
            parentId: 1,
            menuName: '角色管理',
            menuType: 2,
            path: '/system/role',
            component: 'system/role/index',
            permission: 'system:role:list',
            icon: 'icon-safe',
            sort: 2,
            visible: 1,
            status: 1,
            isCache: 1,
            createTime: '2024-01-01 00:00:00'
          }
        ]
      },
      {
        id: 2,
        parentId: 0,
        menuName: '系统监控',
        menuType: 1,
        path: '/monitor',
        component: null,
        permission: null,
        icon: 'icon-desktop',
        sort: 2,
        visible: 1,
        status: 1,
        isCache: 0,
        createTime: '2024-01-01 00:00:00',
        children: [
          {
            id: 21,
            parentId: 2,
            menuName: '在线用户',
            menuType: 2,
            path: '/monitor/online',
            component: 'monitor/online/index',
            permission: 'monitor:online:list',
            icon: 'icon-user-group',
            sort: 1,
            visible: 1,
            status: 1,
            isCache: 1,
            createTime: '2024-01-01 00:00:00'
          }
        ]
      }
    ]
    
    tableData.value = mockData
  } catch (error) {
    Message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.menu-container {
  padding: 20px;
}

.search-form {
  background: #f7f8fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.table-actions {
  margin-bottom: 16px;
  
  .arco-btn + .arco-btn {
    margin-left: 8px;
  }
}
</style> 